using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using JmShared;
using Xamarin.ActionbarSherlockBinding.App;
using Fragment = Android.Support.V4.App.Fragment;
using IMenuItem = Xamarin.ActionbarSherlockBinding.Views.IMenuItem;

namespace jivemessenger
{
        [Activity(Label = "Contacts")]
    public class Contacts : SherlockActivity
    {
        private ListView listview;
        private static ContactArrayAdapter adapter;
            //public static Dictionary<UserInfo,DateTime> UsersToAdd = new Dictionary<UserInfo, DateTime>();
            //public static Dictionary<UserInfo, DateTime> UsersToUpdate = new Dictionary<UserInfo, DateTime>();
            //public static Dictionary<UserInfo, DateTime> UsersToDelete = new Dictionary<UserInfo, DateTime>();
            public static bool IsActive;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Contacts);
            // Create your fragment here
            listview = (ListView)FindViewById<ListView>(Resource.Id.listViewContacts);
            adapter = new ContactArrayAdapter(this, Resource.Layout.ContactListItem);
            listview.Adapter = adapter;
            SupportActionBar.SetDisplayShowHomeEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            SupportActionBar.NavigationMode = Xamarin.ActionbarSherlockBinding.App.ActionBar.DisplayHomeAsUp;
            SupportActionBar.SetDisplayShowTitleEnabled(true);
            AddContact(Client.CurrentUserInfo);
            AddContacts(Client.ConnectedClients.Values.ToArray());
            //foreach (var v in UsersToAdd)
            //{
            //    UserInfo toDeleteUser = UsersToDelete.Keys.ToList().Find(x => x.UserID == v.Key.UserID);

            //    if (toDeleteUser != null)
            //    {
            //        DateTime toDeleteTime = UsersToDelete[toDeleteUser];
            //        if (v.Value.Subtract(toDeleteTime).TotalSeconds > 0) //the user was added after it was deleted
            //        {
            //            AddContact(v.Key);
            //            UsersToDelete.Remove(toDeleteUser);
            //        }
            //        //if not, it was added before it was deleted, so we skip it.
            //    }
            //    else
            //        AddContact(v.Key);
               
            //}
            //UsersToAdd.Clear();
            //foreach(var v in UsersToUpdate)
            //{
            //    UserInfo toDeleteUser = UsersToDelete.Keys.ToList().Find(x => x.UserID == v.Key.UserID);

            //    if (toDeleteUser != null)
            //    {
            //        DateTime toDeleteTime = UsersToDelete[toDeleteUser];
            //        if (v.Value.Subtract(toDeleteTime).TotalSeconds > 0) //the user was added after it was deleted
            //        {
            //            UpdateContact(v.Key);
            //            UsersToDelete.Remove(toDeleteUser);
            //        }
            //        //if not, it was added before it was deleted, so we skip it.
            //    }
            //    else
            //        UpdateContact(v.Key);
            //}
            //UsersToUpdate.Clear();
            //foreach (var v in UsersToDelete)
            //{
            //    RemoveContact(v.Key);
            //}
            //UsersToDelete.Clear();
        }
          
        public override bool OnMenuItemSelected(int featureId, IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Android.Resource.Id.Home:
                    Finish(); //?
                    break;
            }
            return true;
        }

            protected override void OnResume()
        {
            base.OnResume();
            IsActive = true;
            //TODO: Load data
        }

            protected override void OnPause()
        {
            IsActive = false;
            base.OnPause();
        }
        //public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
        //{
        //    return inflater.Inflate(Resource.Layout.Contacts, container, false);

        //}
        //public override void OnViewCreated(View view, Bundle savedInstanceState)
        //{
        //    listview = (ListView)view.FindViewById<ListView>(Resource.Id.listViewContacts);
        //    adapter = new ContactArrayAdapter(view.Context, Resource.Layout.ContactListItem);
        //    listview.Adapter = adapter;
        //}

        private static Contact GetAvatarButtonForUser(UserInfo info)
        {
            if (adapter == null)
                return null;
            foreach (Contact contact in adapter.Contacts)
            {

                UserInfo usr = contact.User;
                if (usr.UserName == info.UserName)
                    return contact;
            }
            return null;
        }
        public static void AddContacts(IEnumerable<UserInfo> contacts)
        {
            foreach (UserInfo user in contacts)
            {
                AddContact(user);
            }
        }

            public static  void AddContact(UserInfo user)
            {
                if (adapter == null)
                    return;
                if (Client.ConnectedClients == null)
                    Client.ConnectedClients = new Dictionary<string, UserInfo>();

                if (user == null)
                    return;

                if (user.UserID != Client.CurrentUserInfo.UserID)
                    Client.ConnectedClients[user.UserID] = user;
                if (user.UserName == Client.CurrentUserInfo.UserName)
                {
                    Client.CurrentUserInfo.NickName = user.NickName;
                    Client.CurrentUserInfo.FontStyle = user.FontStyle;
                    Client.CurrentUserInfo.FontName = user.FontName;
                    Client.CurrentUserInfo.Color = user.Color;
                }

                if (GetAvatarButtonForUser(user) == null)
                {
                    UserInfo user1 = user;
                    StaticSettings.GlobalContext.RunOnUiThread(() =>
                    {
                        adapter.add(new Contact(user1));

                    });
                    //this.WriteMessage(Helpers.PrettyName(u) + " has been added to the conversation.", Client.CurrentUserInfo, message.MessageType);
                }
                else //If user is already online, just update info
                {
                    Contact contact = GetAvatarButtonForUser(user);
                    if (contact != null)
                    {
                        //TextBlock tb = btn.FindName("UserName_" + user.UserName) as TextBlock;
                        //if (tb != null)
                        //    tb.Text = user.PrettyName;
                        //  contact.User = user;
                        UpdateContact(user);
                    }

                }
            }

            public static void ClearContacts()
        {
            if (adapter == null)
                return;
            Contact[] foo = new Contact[adapter.GetCount()];
            adapter.Contacts.CopyTo(foo);
            StaticSettings.GlobalContext.RunOnUiThread(() =>
                {
                    foreach (Contact c in foo)
                        adapter.remove(c);
                });
            //this.adapter.NotifyDataSetChanged();
        }

        public static void UpdateContact(UserInfo user)
            {
                if (adapter == null)
                    return;
            StaticSettings.GlobalContext.RunOnUiThread(() =>
                {
                    Contact c = GetAvatarButtonForUser(user);
                    if (c != null)
                    {
                        Contact oldContact = adapter.Contacts.Find(x => x.User.UserName == user.UserName);
                        oldContact.User = user;

                    }
                    //    this.adapter.remove(c);

                    //this.adapter.add(c);
                    adapter.NotifyDataSetChanged();
                });
        }

        public static void RemoveContact(UserInfo contact)
        {
            if (adapter == null)
                return;
            Contact c = GetAvatarButtonForUser(contact);
            StaticSettings.GlobalContext.RunOnUiThread(() =>
                {
                    if (c != null)
                        adapter.remove(c);
                });
            //  this.adapter.NotifyDataSetChanged();
        }
    }
}